﻿using OnlineEducation.Constants;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;

namespace OnlineEducation.Helpers
{
    public class Utility
    {
        public string CreateChecksum(string param,string method)
        {
            // 拼接字符串
            string checksumResult = method+param+ ServerAPI.APIKey;
            return checksumResult;
        }

        public static string CreateParams(string method)
        {
            string checksumPara = method + ServerAPI.APIKey;
            // 计算SHA-1
            var checksum = SHA1Result(checksumPara);
            return  "checksum=" + checksum;
        }

        public static string CreateParams<T>(T param,string method)
        {
            string paras = string.Empty;

            foreach (var item in param.GetType().GetProperties())
            {
                var value = item.GetValue(param, null);
                if (value != null)
                {
                    
                        paras = paras + item.Name + "=" + System.Net.WebUtility.UrlEncode(item.GetValue(param, null).ToString()) + "&";
                }

            }
            paras = paras.Replace("&meta=", "&");
            string checksumPara = method + paras.TrimEnd('&') +  ServerAPI.APIKey;
            // 计算SHA-1
            var checksum = SHA1Result(checksumPara);
            return paras + "checksum=" + System.Net.WebUtility.UrlEncode(checksum);
        }

        private static string SHA1Result(string content)
        {
            try
            {
                byte[] temp1 = Encoding.UTF8.GetBytes(content);
                SHA1CryptoServiceProvider sha = new SHA1CryptoServiceProvider();
                byte[] temp2 = sha.ComputeHash(temp1);
                sha.Clear();
                // 注意， 不能用这个
                // string output = Convert.ToBase64String(temp2);// 不能直接转换成base64string
                var output = BitConverter.ToString(temp2);
                output = output.Replace("-", "");
                output = output.ToLower();
                return output;
            }
            catch (Exception ex)
            {
                throw new Exception("SHA1加密出错：" + ex.Message);
            }
        }

        public static T XMLToModel<T>(string xml)
        {
          
 

            XmlSerializer serializer = new XmlSerializer(typeof(T));

            TextReader textReader = new StringReader(xml);

            return (T)serializer.Deserialize(textReader);

 

        }
    }
}
